//
//  MyPostsViewController.m
//  parent
//
//  Created by IreWesT on 15/5/29.
//  Copyright (c) 2015年 ci123. All rights reserved.
//

#import "MyPostsViewController.h"
#import "MyPostsTableViewCell.h"
#import "MyPostsTableViewCell.h"
#import "MyReplyTableViewCell.h"
#import "MJRefresh.h"
#import "DetailNewViewController.h"

@interface MyPostsViewController ()<
    UITableViewDelegate,
    UITableViewDataSource
>

@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UITableView *replyTableView;

@property (nonatomic, assign) NSInteger currentTag;
@property (nonatomic, retain) NSMutableArray *postData;
@property (nonatomic, copy) NSString *postPicPrefix;
@property (nonatomic, retain) NSMutableArray *replyData;
@property (nonatomic, copy) NSString *replyPicPrefix;
@property (nonatomic, retain) NSArray *circleNames;

@end

@implementation MyPostsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _currentTag = 1;
    
    WS(weakSelf);
    UIView *titleView = [self createNavCenterSilderWithNames:@[@"发帖",@"回帖"]
                                       withBlock:^(NSInteger index){
                                           __strong typeof (weakSelf) strongSelf = weakSelf;
                                           if (!strongSelf || _currentTag == index) {
                                               return;
                                           }
                                           
                                           _currentTag = index;
                                           
                                           [strongSelf switchTableView];
                                           NSLog(@"tag:%ld", (long)_currentTag);
                                       }isWider:YES];
    
    self.navigationItem.titleView = titleView;
    
    [self _initView];
    [self _initData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark  - UI

- (void)_initView {
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT) style:UITableViewStylePlain];
    _tableView.backgroundColor = UIColorMake(244, 244, 244);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    _replyTableView = [[UITableView alloc] initWithFrame:CGRectMake(APP_SCREEN_WIDTH, 0, APP_SCREEN_WIDTH, APP_SCREEN_HEIGHT - self.navHeight) style:UITableViewStylePlain];
    _replyTableView.backgroundColor = UIColorMake(244, 244, 244);
    _replyTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _replyTableView.delegate = self;
    _replyTableView.dataSource = self;
    [self.view addSubview:_replyTableView];
    
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 20 , 44, 44)];
    button.showsTouchWhenHighlighted = YES;
    button.backgroundColor = [UIColor clearColor];
    button.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 30);
    [button setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
}
-(void)backButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)switchTableView {

    [UIView animateWithDuration:0.3f
                     animations:^(void){
                     
                         if (_currentTag == 1) {
                             _tableView.left = 0;
                             _replyTableView.left = APP_SCREEN_WIDTH;
                         }else {
                         
                             _tableView.left = -APP_SCREEN_WIDTH;
                             _replyTableView.left = 0;
                         }
                     }
                     completion:^(BOOL finished){
                     
                         [self headerRereshing];
                     }];
}

#pragma mark - Data

- (void)_initData {

    _circleNames = @[@"班级圈",@"育儿经",@"大杂烩"];
    _postData = [[NSMutableArray alloc] init];
    _replyData = [[NSMutableArray alloc] init];
    
    [self setUpRefreshPlugin];
}

- (void)dealPosts:(NSDictionary *)dic isReload:(BOOL)isReload {
    
    if (!dic || dic.count <=0 || ![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    if (isReload) {
        [_postData removeAllObjects];
    }
    
    _postPicPrefix = [NSString stringWithFormat:@"%@", dic[@"avatar_header"]];
    
    for (NSDictionary *subDic in dic[@"posts"]) {
        [_postData addObject:subDic];
    }
    
    [_tableView reloadData];
}

- (void)dealReply:(NSDictionary *)dic isReload:(BOOL)isReload {
    
    if (!dic || dic.count <=0 || ![dic isKindOfClass:[NSDictionary class]]) {
        return;
    }
    
    if (isReload) {
        [_replyData removeAllObjects];
    }
    
    _replyPicPrefix = [NSString stringWithFormat:@"%@", dic[@"avatar_header"]];
    
    for (NSDictionary *subDic in dic[@"replys"]) {
        [_replyData addObject:subDic];
    }
    
    [_replyTableView reloadData];
}

#pragma mark - Networking

- (BOOL)apiGetMyPosts:(NSString*)requestType baseId:(NSString *)baseId{
    
    
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"dir":requestType,
                                @"baseid":baseId};
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"USER_GET_OWN_ARTICLES";
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if ([requestType isEqualToString:@"new"]) {
            [self stopHeaderRefresh];
        }else if ([requestType isEqualToString:@"old"]){
            [self stopFooterRefresh];
        }
        
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue]== 1) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        NSLog(@"posts:%@", dict);
                        [self dealPosts:dict isReload:YES];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        NSLog(@">>>>%@",dict);
                        [self dealPosts:dict isReload:NO];
                    }
                }else if ([[dict objectForKey:@"retCode"] integerValue]== 10020) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"您还没有发帖" cancelButtonTitle:@"确定"];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"没有更多了哦~" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
    return YES;
}

-(BOOL)apiGetMyReply:(NSString*)requestType baseId:(NSString *)baseId {
    
    NSString* uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString* utype = @"1";
    
    NSDictionary *temp_dict = @{@"uid":uid,
                                @"utype":utype,
                                @"token":[[UserDao getInstance]getAccessToken],
                                @"dir":requestType,
                                @"baseid":baseId};
    
    NSString *dataString = [JsonUtil convertDictionaryToJson:temp_dict];
    
    NSString *msg = @"USER_GET_OWN_REPLYS";
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    
    [[NetWorkManager getInstanse] requestURLAsynMessage:msg data:dataString FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if ([requestType isEqualToString:@"new"]) {
            [self stopHeaderRefresh];
        }else if ([requestType isEqualToString:@"old"]){
            [self stopFooterRefresh];
        }
        
        if (connectionError) { //连接失败
            NSLog(@"Http Error: %@   %ld", connectionError.localizedDescription,(long)connectionError.code);
            NSString *error_content = [NSString stringWithFormat:@"连接错误:%ld",(long)connectionError.code];
            [popUIMgr popAlertView:nil title:@"提示" message:error_content cancelButtonTitle:@"确定"];
        }else{//连接成功，判断是否有数据返回
            if (data) {
                NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
                if ([[dict objectForKey:@"retCode"] integerValue]== 1) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        NSLog(@"reply:%@", dict);
                        [self dealReply:dict isReload:YES];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [self dealReply:dict isReload:NO];
                    }
                }else if ([[dict objectForKey:@"retCode"] integerValue]== 10020) {
                    if ([requestType isEqualToString:@"new"]) { //下拉 获取最新数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"您还没有回帖" cancelButtonTitle:@"确定"];
                    }else if ([requestType isEqualToString:@"old"]){//上拉 加载更多旧数据的回调
                        [popUIMgr popAlertView:nil title:@"提示" message:@"没有更多了哦~" cancelButtonTitle:@"确定"];
                    }
                }else{
                    [popUIMgr popAlertView:nil title:@"提示" message:@"数据解析错误" cancelButtonTitle:@"确定"];
                }
            }else{
                [popUIMgr popAlertView:nil title:@"提示" message:@"服务器没有返回数据" cancelButtonTitle:@"确定"];
            }
        }
        [popUIMgr removeWaitingUI];
    }];
    return YES;
}

/**
 *  集成刷新控件
 */
#pragma mark - MJRefresh

- (void)setUpRefreshPlugin {
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [_replyTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [_replyTableView addFooterWithTarget:self action:@selector(footerRereshing)];
    
    //设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _tableView.headerPullToRefreshText = @"下拉刷新";
    _tableView.headerReleaseToRefreshText = @"松开刷新";
    _tableView.headerRefreshingText = @"正在刷新...";
    _replyTableView.headerPullToRefreshText = @"下拉刷新";
    _replyTableView.headerReleaseToRefreshText = @"松开刷新";
    _replyTableView.headerRefreshingText = @"正在刷新...";
    
    _tableView.footerPullToRefreshText = @"上拉加载";
    _tableView.footerReleaseToRefreshText = @"松开加载";
    _tableView.footerRefreshingText = @"正在加载...";
    _replyTableView.footerPullToRefreshText = @"上拉加载";
    _replyTableView.footerReleaseToRefreshText = @"松开加载";
    _replyTableView.footerRefreshingText = @"正在加载...";
}

- (void)startHeaderRefresh{
    //刷新
    if (_currentTag == 1) {
        [_tableView headerBeginRefreshing];
    }else {
        [_replyTableView headerBeginRefreshing];
    }
}

//================顶部刷新，获取最新动态=========================
//首次进入会自动执行一次获取最新动态
- (void)headerRereshing
{
    if ([NetWorkManager connectedToNetwork]) {
        if (_currentTag == 1) {
            [self apiGetMyPosts:@"new" baseId:@"-1"];
        }else {
            [self apiGetMyReply:@"new" baseId:@"-1"];
        }
    }else{
        //没有网络的情况下，加载本地缓存数据
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

//================底部刷新，获取最新动态=========================
- (void)footerRereshing
{
    
    if([NetWorkManager connectedToNetwork]) {
        if (_currentTag == 1) {
            NSString *baseId = [NSString stringWithFormat:@"%@", ((NSDictionary *)_postData.lastObject)[@"postid"]];
            NSLog(@"%@", baseId);
            [self apiGetMyPosts:@"old" baseId:baseId];
        }else {
            NSString *baseId = [NSString stringWithFormat:@"%@", ((NSDictionary *)_replyData.lastObject)[@"replyid"]];
            NSLog(@"%@", baseId);
            [self apiGetMyReply:@"old" baseId:baseId];
        }
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"网络连接断开" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}

-(void) stopHeaderRefresh {
    
    [self.tableView headerEndRefreshing];
    [self.replyTableView headerEndRefreshing];
}

-(void) stopFooterRefresh {
    
    [self.tableView footerEndRefreshing];
    [self.replyTableView footerEndRefreshing];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (tableView == _tableView) {
        return PostHeight;
    }else {
        return ReplyHeight;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *pid ;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == _tableView) {
        pid= _postData[indexPath.row][@"postid"];
    }else {
       pid =  _replyData[indexPath.row][@"post_id"];
    }
   
    DetailNewViewController *detail = [[DetailNewViewController alloc]init];
    detail.msgId = pid;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];

}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (tableView == _tableView) {
        return _postData.count;
    }else {
        return _replyData.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _tableView) {
        static NSString *CellIdentifier = @"CellStyleMyPost";
        
        MyPostsTableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil) {
            cell = [[MyPostsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.backgroundColor = UIColorMake(244, 244, 244);
        }
        
        cell.pic = [[UserDao getInstance] getUserInfo].avatar;
        cell.name = [[UserDao getInstance] getUserInfo].nickName;
        cell.circleName = _circleNames[[_postData[indexPath.row][@"type"] integerValue] - 1];
        cell.data = _postData[indexPath.row];

        return cell;
    }else {
        static NSString *CellIdentifier = @"CellStyleMyReply";
        
        MyReplyTableViewCell *cell = [_replyTableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if(cell == nil) {
            cell = [[MyReplyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            cell.backgroundColor = UIColorMake(244, 244, 244);
        }
        
        cell.pic = [[UserDao getInstance] getUserInfo].avatar;
        cell.name = [[UserDao getInstance] getUserInfo].nickName;
        cell.circleName = _circleNames[[_replyData[indexPath.row][@"srcpost"][@"type"] integerValue] - 1];
        cell.data = _replyData[indexPath.row];
        
        return cell;
    }
}

@end
